#!/usr/bin/env python3
# -*- coding: utf-8 -*-


from optparse import OptionParser
from sys import argv, stdin
from xml.etree import ElementTree as etree


def wikified_title(text):
    """Returns string converted accordingly to mediawiki conventions.
    """
    text = text.strip()
    text = text.replace(' ', '_')
    text = text.replace('\xa0', '_')
    text = text.replace('\n', '_')
    return text


class WikiPage:
    pass


class RuWikisourcePage(WikiPage):
    pass


class RuWikisourceBook:
    
    def __init__(self, filename):
        
        self.setTitle(filename) # sets default title and wikititle
        self.bookinfo = {
            'abstract': '',
            'author': '',
            'translator': '',
        }
        self.prefaces = []
        self.chapters = []
        
        tree = etree.parse(
            stdin if filename=='-' else filename
        )
        
        book = tree.getroot()
        assert book.tag == 'book', book.tag
        
        self.process_element(book)
    
    def setTitle(self, text):
        self.title = text
        self.wikititle = wikified_title(text)
    
    
    def process_element(self, element):
        """Process book-specific element
        """
        passed_elements = (
            'book',
        )
        
        if element.tag in passed_elements:
            for subelem in element:
                self.process_element(subelem)
        
        elif element.tag == 'bookinfo':
            for sub in element:
                if sub.tag == 'authorgroup':
                    for subsub in sub:
                        if   subsub.tag == 'author':
                            self.bookinfo['author'] = xml_to_wiki(subsub)
                        elif subsub.tag == 'translator':
                            self.bookinfo['translator'] = xml_to_wiki(subsub)
                elif sub.tag == 'abstract':
                    self.bookinfo['abstract'] = xml_to_wiki(sub)
                else:
                    self.process_element(sub)
            print('----', self.bookinfo)
        
        elif element.tag == 'title':
            self.setTitle(element.text)
        
        else:
            raise NotImplementedError(element.tag, element.attrib, element.text, [sub.tag for sub in element])
    
    def xml_to_wiki(self.element):
        """Convert book-inspecific element to wiki code.
        """
        passed_elements = (
        )
        
        if element.tag in passed_elements:
            for subelem in element:
                self.xml_to_wiki(subelem)
        
        elif element.tag == 'author':
            self.bookinfo['author'] = element.text.strip()
            return ''.join(self.xml_to_wiki(sub) for sub in element).strip()
        
        else:
            raise NotImplementedError(element.tag, element.attrib, element.text, [sub.tag for sub in element])
        
        return ''


def make_books(source_filenames):
    books = [ RuWikisourceBook(fn) for fn in source_filenames ]


if __name__ == '__main__':
    
    parser = OptionParser(
        usage='%prog [OPTIONS] FILE',
        description='Converts XML FILE to a set of mediawiki pages for publishing to Ru.Wikisource.org'
    )
    parser.add_option('-o', '--output-directory',
        action='store', dest='output_directory', default='.',
        help='directory to save files', metavar='DIR'
    )
    (options, args) = parser.parse_args()
    
    make_books(args)
